package com.j.lemon.learn.waitnotify;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ProcessTask{

    private long timeMark ;

    private final Object lock = new Object();
    private int time = 3;
    private List<String> messages = new ArrayList<>();
    private void process(String msg) throws InterruptedException {
        String name = Thread.currentThread().getName();
        synchronized (lock){

            log.info(name+":时间任务没有在执行");
            messages.add(msg);
        }

    }

    private void startThread(){
        ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(1);
        threadPoolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                String name = Thread.currentThread().getName();
                if((System.currentTimeMillis()-timeMark) >= (time*1000L)){
                    synchronized (lock){
                        log.info(name+":事件间隔达到{}秒， 开始批量插入",time);
                        log.info(name+":处理中");
                        try {
                            Thread.sleep(3000L);
                            log.info(name+":messages size :{}",messages.size());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        messages.clear();
                        timeMark = System.currentTimeMillis();
                        log.info(name+":事件间隔处理结束");
                    }
                }
            }
        },0,1, TimeUnit.SECONDS);
    }

    public static void main(String[] args) throws InterruptedException {
        ProcessTask processTask = new ProcessTask();
        processTask.startThread();
            processTask.process("222");
            processTask.process("222");
            processTask.process("222");
            Thread.sleep(5000L);

    }

}
